<?php

namespace app\services;

use app\payment\PayFactory;
use app\traits\Page;
use plugin\admin\app\model\Activity;
use plugin\admin\app\model\ActivityUser;
use plugin\admin\app\model\Order;
use plugin\admin\app\model\UserActivity;

class UserActivityService
{
    public static function list($page = 1, $length = 10, $status = 0)
    {
        $offset = ($page - 1) * $length;
        $query = Order::where('user_id', get_user_id())->whereNull('delete_time');

        if ($status > 0) {
            if ($status != 7) {
                $query->where('status', $status)->where('refund_status', 0);
            } else {
                $query->where('refund_status', '>', 0);
            }
        }

        $totalCount = (clone $query)->count();
        $list = $query->select(['id', 'user_id', 'order_no', 'price', 'pay_time', 'cancel_time', 'pay_way', 'status', 'refund_status', 'refund_type', 'refund_desc', 'refund_amount', 'info', 'created_time'])->orderByDesc('created_time')->offset($offset)->limit($length)->get()->toArray();

        foreach ($list as $key=>$item) {
            $info = json_decode($item['info'], true);
            $thumbs = explode(',', $info['activity']['thumbs']);

            foreach ($thumbs as $key2=>$thumb) {
                $thumbs[$key2] = full_url($thumb);
            }

            $info['activity']['thumbs'] = $thumbs;

            $list[$key]['info'] = $info;

            $list[$key]['status_text'] = Order::getStatusText($item);
            $list[$key]['refund_status_text'] = Order::getRefundStatusText($item['refund_status']);
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function detail($orderNo)
    {
        $res = Order::where('user_id', get_user_id())->select(['id', 'user_id', 'order_no', 'price', 'pay_time', 'cancel_time', 'pay_way', 'status', 'refund_status', 'refund_type', 'refund_desc', 'refund_amount', 'info', 'created_time'])->where('order_no', $orderNo)->first()->toArray();

        $res['info'] = json_decode($res['info'], true);

        $thumbs = explode(',', $res['info']['activity']['thumbs']);

        foreach ($thumbs as $key2=>$thumb) {
            $thumbs[$key2] = full_url($thumb);
        }

        $res['info']['activity']['thumbs'] = $thumbs;
        $res['status_text'] = Order::getStatusText($res);
        $res['refund_status_text'] = Order::getRefundStatusText($res['refund_status']);
        $res['rest_pay_time'] = OrderService::getRestPayTime($res);

        return $res;
    }

    public static function join($activityId, $personInfos)
    {
        $activityInfo = Activity::where('id', $activityId)->first();

        if (!$activityInfo) {
            throw new \Exception('不存在的活动');
        }

        if ($activityInfo['min_count'] > count($personInfos)) {
            throw new \Exception('参与人数不能小于' . $activityInfo['min_count'] . '个');
        }

        $rest = $activityInfo['max_count'] - $activityInfo['join_count'] - $activityInfo['freeze_count'];

        if ($rest < count($personInfos)) {
            if ($rest == 0) {
                throw new \Exception('该活动已无名额，请选择其他活动');
            } else {
                throw new \Exception('该活动剩余名额仅剩' . $rest . '个');
            }
        }

        foreach ($personInfos as $key => $personInfo) {
            self::checkPersonInfo($key, $personInfo);
        }

        $info = ['activity' => $activityInfo, 'personInfos' => $personInfos];

        $price = bcmul(count($personInfos), $activityInfo['price'], 2);

        $orderNo = OrderService::generateOrderNo();
        [$payWay, $payWayType] = self::getPayWay();

        ActivityService::freeze($activityId, count($personInfos));

        Order::insert([
            'user_id' => get_user_id(),
            'activity_id' => $activityId,
            'order_no' => $orderNo,
            'price' => $price,
            'type' => Order::TYPE_ACTIVITY,
            'pay_way' => $payWay,
            'pay_way_type' => $payWayType,
            'created_time' => date('Y-m-d H:i:s'),
            'info' => json_encode($info, JSON_UNESCAPED_UNICODE),
            'status' => Order::STATUS_WAITING_PAY
        ]);

        return $orderNo;
    }

    public static function insertPersons($order)
    {
        $info = json_decode($order['info'], true);
        $insertData = [];

        foreach ($info['personInfos'] as $personInfo) {
            $insertData[] = [
                'activity_id' => $order['activity_id'],
                'name' => $personInfo['name'],
                'mobile' => $personInfo['mobile'],
                'sex' => $personInfo['sex'],
                'idcard' => $personInfo['idcard'] ?? '',
                'created_time' => date('Y-m-d H:i:s')
            ];
        }

        ActivityUser::insert($insertData);
    }

    protected static function getPayWay()
    {
        if (getenv('ENV') == 'test' || getenv('ENV') == 'prod') {
            return [PayFactory::WECHAT, 'mini'];
        } else {
            return [PayFactory::BALANCE, ''];
        }
    }

    protected static function checkPersonInfo($key, $personInfo)
    {
        if (empty($personInfo['name']) || empty($personInfo['mobile'])) {
            throw new \Exception('第' . ($key + 1) . '个游客的信息不完整');
        }
    }
}